const LENGTH = 20;
import { EventBus } from '@/store/index'
import BaseCreatejs from '@/components/games/createjs/js/BaseCreatejs.js'
import { MOBILE_WID_HEI } from '@/common/const-dif'
import { getCompIdByParam } from '@/plugins/utils'


export default class JdQixiFestival extends BaseCreatejs {

	constructor() {
		super();

		this.questions;//7个问题页面组合
		this.home;//主页面
		this.wrongs;//错误弹层页面
		this.right;//错误弹层页面
		this.questionIndex = 0;//记录当点答题答到哪道题的索引
		this.blackIndex = 0;//记录当点答案索引
		this.randomIndex = 0;//随机问题也的索引
		this.words = [];//每个页面的点击字的数组
		this.blacks = [];//每个问题页面的答案字的数组
		//回答和答案不统一，现在发现的有包治百病和爱情面包对应错了，珍惜到秒对应了每时每刻
		//bag lipstick eyecream essence perfume jewelry watch
		this.questionsTexts = [
			[['不', '装', '百', '包', '治', '变', '准', '志', '标', '病'], ['安', '美', '爱', '包', '面', '奇', '情', '全', '白', '请']],
			[['我', '典', '还', '一', '好', '用', '味', '玩', '到', '点'], ['红', '生', '花', '送', '号', '色', '好', '深', '四', '活']],
			[['墨', '切', '以', '霾', '前', '闷', '幽', '一', '阴', '欲'], ['动', '笑', '对', '心', '现', '喜', '下', '倒', '逗', '大']],
			[['日', '处', '福', '修', '如', '幸', '常', '复', '出', '初'], ['的', '暗', '缩', '当', '你', '爱', '大', '示', '适', '浓']],
			[['度', '闻', '味', '的', '吻', '我', '到', '道', '独', '唯'], ['贞', '自', '香', '心', '造', '型', '惜', '信', '真', '珍']],
			[['此', '不', '彼', '珠', '专', '质', '珠', '杂', '注', '掺'], ['过', '风', '贴', '忑', '跟', '剔', '体', '分', '挑', '忐']],
			[['时', '数', '每', '秒', '空', '没', '术', '刻', '每', '魔'], ['钟', '香', '秒', '当', '惜', '相', '面', '珍', '到', '真']]
		];
		this.itemNames = ["Bag", "Lipstick", "Eyecream", "Essence", "Perfume", "Jewelry", "Watch"]
    this.itemGifUrls = [
      ["https://static.hd.xxx.com/upload/biz/36/7921864_1149.gif", "https://static.hd.xxx.com/upload/biz/36/40925883_1149.gif"],
      ["https://static.hd.xxx.com/upload/biz/36/27149837_1149.gif", "https://static.hd.xxx.com/upload/biz/36/13598368_1149.gif"],
      ["https://static.hd.xxx.com/upload/biz/36/51238537_1149.gif", "https://static.hd.xxx.com/upload/biz/36/71939500_1149.gif"],
      ["https://static.hd.xxx.com/upload/biz/36/7107345_1149.gif", "https://static.hd.xxx.com/upload/biz/36/50098806_1149.gif"],
      ["https://static.hd.xxx.com/upload/biz/36/25469420_1149.gif", "https://static.hd.xxx.com/upload/biz/36/64649191_1149.gif"],
      ["https://static.hd.xxx.com/upload/biz/36/36197275_1149.gif", "https://static.hd.xxx.com/upload/biz/36/36197275_1149.gif"],
      ["https://static.hd.xxx.com/upload/biz/36/29916421_1149.gif", "https://static.hd.xxx.com/upload/biz/36/77671758_1149.gif"],
    ]
    // this.itemScales = [
    //   [, ],
    //   [, ],
    //   [, ],
    //   [, ],
    //   [, ],
    //   [, ],
    //   [, ],
    // ]
		this.rightAnswers = [
			[[3, 4, 2, 9], [2, 6, 4, 3]],
			[[2, 0, 3, 9], [5, 4]],
			[[7, 1, 8, 3], [9, 1]],
			[[3, 7, 4, 9], [9, 2, 0, 5]],
			[[5, 3, 2, 7], [8, 2]],
			[[1, 9, 7, 5], [0, 7, 8, 5]],
			[[2, 0, 8, 7], [7, 4, 8, 2]],
		];
		this.rightObj = {};
	}

  defaultNullClick(){
    console.log("啥也不做，阻止事件");
  }

	initView(lib) {
		this.lib = lib;
		this.stage.addChild(this.stagePage);
		this.home = this.stagePage.home;
		let btns = this.home.btns;
		let animates = this.home.animates;
    this.home.on("click", this.defaultNullClick);

    // let questionGif = [];
    // for(let i = 0; i < this.itemNames.length; i++){
    //   let xx = [];
    //   let gifCon = new lib[this.itemNames[i] + "_0"];
    //   xx.push(gifCon.gif.scale);
    //   gifCon = new lib[this.itemNames[i] + "_1"];
      
    //   xx.push(gifCon.gif.scale);
    //   questionGif.push(xx);
    // }

		window.setTimeout(() => {
			btns.gotoAndPlay(0);
			animates.gotoAndPlay(0);
		}, 50)

    btns.btnNow.mouseChildren = false
		btns.btnNow.addEventListener("click", () => {
      this.home.animates.stop();
			this.home._off = true;
			this.home.parent.removeChild(this.home);
      this.home.off("click", this.defaultNullClick);


			btns.btnNow.removeAllEventListeners();

			this.questions = new this.lib.Questions();
      this.questions.on("click", this.defaultNullClick);

			this.stage.addChild(this.questions);
			this.questionIndex = 0;

			this.wrongs = new this.lib.Wrongs();
      this.wrongs.on("click", this.defaultNullClick);

			// this.stage.addChild(this.wrongs);
			this.wrongs.btnNext.mouseChildren = false;
			this.wrongs.btnNext.addEventListener('click', () => {
        // this.wrongs.wrong.gif.stop();
				this.wrongs._off = true;
				this.wrongs.parent.removeChild(this.wrongs);

				this.addQuestionByIndex(this.questionIndex);
				this.nextQuestion();
			})

			this.right = new this.lib.Right();
      this.right.on("click", this.defaultNullClick);

			// this.stage.addChild(this.right);
			this.right.btnNext.mouseChildren = false;
			this.right.btnNext.addEventListener('click', () => {
				this.right._off = true;
				this.right.parent.removeChild(this.right);

        this.questions.gif.visible = true
        this.addQuestionByIndex(this.questionIndex);
				this.nextQuestion();
			});
			this.hiddenComps();

			this.addQuestionByIndex(this.questionIndex);
			this.showQuestionMask();
      this.initQuestions();
		});
	}

	addQuestionByIndex(questionIndex) {
		if (this.questions.question) {
      this.questions.question._off = true;
			this.questions.removeChild(this.questions.question);
		}

    let randomIndex = this.randomIndex = _.random(0, 1);
		let QuestionClass = this.itemNames[questionIndex] + "_" + randomIndex;
		let question = null;
		if (QuestionClass) {
			question = new this.lib[QuestionClass]();
			// if(this.isLowVersion){
			// 	question.gif.stop();
			// }
      // this.createSpriteSheetBuilder(question);

      // question.gif.stop();
      // question.gif._off = true;
      // question.removeChild(question.gif);

      let url = this.itemGifUrls[this.questionIndex][this.randomIndex];
      if(this.questions.gif){
        this.questions.gif.y = 0;
        this.questions.gif.scaleX = 1;
        this.questions.gif.scaleY = 1;
      }
      let img = null;
      if(this.questionImg){
        img = this.questionImg;
        img.src = url;
      }else{
        img = new Image();
        img.src = url;
        img.onload = (e) => {
          let img_ = e.target;
          img_.style.width = img.naturalWidth/MOBILE_WID_HEI.designScale + "px";
          img_.style.height = img.naturalHeight/MOBILE_WID_HEI.designScale + "px";
          img_.style.left = (750 - img.naturalWidth)/MOBILE_WID_HEI.designScale/2 + "px";
          img_.style.top = (700 - img.naturalHeight)/MOBILE_WID_HEI.designScale/2 + "px";
          img.style.transformOrigin = "50% 50%";
        }
        img.style.top = 0;
        img.style.left = 0;
        img.style.transformOrigin = "50% 50%";
        let pages = document.getElementsByClassName("canvas-con")[0];
        pages.appendChild(img);
        this.questionImg = img;
        this.questions.gif = new window.createjs.DOMElement(img);
        this.questions.addChild(this.questions.gif);
      }

			this.questions.question = question;
			this.questions.addChild(question);
      this.refreshQuestion();
		}
		return question;
	}

  initQuestions() {
    let questions = this.questions;
		questions.btnSkip.mouseChildren = false;
		questions.btnSubmit.mouseChildren = false;
		questions.btnSkip.removeAllEventListeners();
		questions.btnSkip.addEventListener('click', () => {
			this.questionIndex++;
			if (this.itemNames[this.questionIndex]) {
				this.addQuestionByIndex(this.questionIndex);
			} else {
				this.completeAnswer();
			}
		})
		questions.btnSubmit.removeAllEventListeners();
		questions.btnSubmit.addEventListener('click', () => {
      // this.questions.question.gif.stop();

			let isRight = false;
			let rights = this.rightAnswers[this.questionIndex][this.randomIndex];
			let selectedAnswers = [];
			_.forEach(this.blacks, (blackItem) => {
				if (blackItem.wordIndex >= 0) {
					selectedAnswers.push(blackItem.wordIndex);
				}
			});
			let intersections = _.intersection(rights, selectedAnswers);
			if (intersections.length == rights.length) {
        isRight = true;
				this.rightObj[this.questionIndex] = true;
			}
			if (isRight) {
				this.right._off = false;
        this.questions.gif.visible = false;
				this.stage.addChild(this.right);
				this.wrongs._off = true;
				this.stage.removeChild(this.wrongs);
			} else {
				this.right._off = true;
				this.stage.removeChild(this.right);
				this.wrongs._off = false;
				this.stage.addChild(this.wrongs);
				this.addWrongByIndex(this.questionIndex);
			}
		})
	}

	addWrongByIndex(questionIndex) {
		if (this.wrongs.wrong) {
			this.wrongs._off = true;
			this.wrongs.removeChild(this.wrongs.wrong);
		}
    this.questions.gif.scaleX = 0.6;
    this.questions.gif.scaleY = 0.6;
    this.questions.gif.y = 100;
    this.questionImg.style.transformOrigin = "center center";
		let WrongClass = this.itemNames[questionIndex];
		let wrong
		if (WrongClass) {
			wrong = new this.lib[WrongClass + "Wrong" + "_" + this.randomIndex];
			// if(this.isLowVersion){
			// 	wrong.gif.stop();
			// }
			this.wrongs.wrong = wrong;
			this.wrongs.addChild(wrong);
		}
		return wrong;
	}

	hiddenComps() {
		if (this.item.commonAttr.hiddenCompIds) {
			let hiddenCompIds = this.item.commonAttr.hiddenCompIds.split(',')
			_.forEach(hiddenCompIds, (compIds) => {
				let compId = getCompIdByParam(compIds);
				if (compId) {
					let params = { id: compId, commonAttr: { isVisible: false } }
					this.store.commit('updateComponentAttr', params);
				}
			})
		}
	}

	showQuestionMask() {
    // this.questions.question.gif.stop();
    this.questions.gif.visible = false;

		let questionMask = new this.lib.QuestionMask();
		questionMask.mouseChildren = false
		this.stage.addChild(questionMask);
    questionMask.on("click", this.defaultNullClick);

		questionMask.addEventListener('click', () => {
      this.questions.gif.visible = true;
			// if(!this.isLowVersion){
      // }
      // this.questions.question.gif.gotoAndPlay(0);

      questionMask.off("click", this.defaultNullClick);
			questionMask._off = true;
			this.stage.removeChild(questionMask);
		});
	}

	nextQuestion() {
		let question = this.questions.question;
    // if(question){
    //   question.gif.stop();
    //   question._off = true;
    //   question.parent.removeChild(question);
    // }

		this.destroyQuestion(question);

		this.questionIndex++;
		if (this.itemNames[this.questionIndex]) {
      this.addQuestionByIndex(this.questionIndex);
		} else {
			this.completeAnswer()
		}
	}

	destroyQuestion(question) {
		let wordItem;
		for (let i = 0; i < LENGTH; i++) {
			wordItem = question["word_" + i];
			if (wordItem) {
				wordItem.removeAllEventListeners();
			}
		}
	}

	completeAnswer() {
		//完成 做对的题数
		let rightAnswerNum = _.size(this.rightObj);
		let relateCompIds = this.item.commonAttr.relateCompIds.split(',');
		_.forEach(relateCompIds, (relateId) => {
			let relateCompId = getCompIdByParam(relateId);
			if (relateCompId) {
				let itemIndex = rightAnswerNum;
				let relateCompData = this.componentMap[relateCompId];
				if (relateCompData) {
					let params;
					params = { id: relateCompId, commonAttr: { itemIndex } }
					this.store.commit('updateComponentAttr', params);
				}
			}
		})
		EventBus.$emit("itemClick", { id: this.item.id, index: 0, e: null });
	}

	refreshQuestion() {
		let questions = this.questions;
		let question = this.questions.question;
		this.blackIndex = 0;

    let titleCon = questions.title_con;
    let titleChilds = titleCon.children;
    let title = null;
    for(let i = 0; i < titleChilds.length; i++){
      title = titleChilds[i];
      title._off = true;
      title.parent.removeChild(title);
    }
    title = new this.lib["Title" + (this.questionIndex + 1)];
    titleCon.addChild(title);

		let words = this.words;
		let blacks = this.blacks;
		while (words.length > 0) {
			words.pop();
		}
		while (blacks.length > 0) {
			blacks.pop();
		}
		let wordItem;
		let blackItem;
		for (let i = 0; i < LENGTH; i++) {
			wordItem = questions["word_" + i];
			blackItem = question["black_" + i];

			if (wordItem) {
				let texts = this.questionsTexts[this.questionIndex][this.randomIndex];
				wordItem.normal.visible = true;
				wordItem.selected.visible = false;

				wordItem.mouseChildren = false;

				words.push(wordItem);
				wordItem.index_ = words.length - 1;
				wordItem.normal.uncache();
				wordItem.normal.txt.text = texts[wordItem.index_];
				let rect = wordItem.normal.nominalBounds;
				wordItem.normal.cache(0, 0, rect.width, rect.height);
				wordItem.normal.updateCache();

				wordItem.selected.uncache();
				wordItem.selected.txt.text = texts[wordItem.index_];
				rect = wordItem.selected.nominalBounds;
				wordItem.selected.cache(0, 0, rect.width, rect.height);
				wordItem.selected.updateCache();

				wordItem.removeAllEventListeners();
				wordItem.addEventListener('click', (e) => {
					this.onWordItem(e);
				});
			}
			if (blackItem) {
				blackItem.mouseChildren = false;
				blacks.push(blackItem);
				blackItem.index_ = blacks.length - 1;
				let rect = blackItem.nominalBounds;
				blackItem.cache(0, 0, rect.width, rect.height);
			}
		}
	}

	onWordItem(e) {
		let targetItem = e.target;
		if (targetItem.selected.visible) {
			this.onCloneItem({ target: targetItem.cloneItem });
			return
		}

		let clickblackItemNum = 0;
		let blackIndex_ = -1;
		let isBlack = true;
		_.forEach(this.blacks, (blackItem, i) => {
			if (blackItem.isSelected) {
				clickblackItemNum++;
			} else {
				if (isBlack) {
					blackIndex_ = i;
					isBlack = false;
				}
			}
		})
		if (!this.blacks[this.blackIndex] && blackIndex_ != -1) {
			this.blackIndex = blackIndex_;
		}
		//都点击过了就返回
		if (clickblackItemNum >= this.blacks.length) {
			return;
		}

		targetItem.normal.visible = false;
		targetItem.selected.visible = true;

		let cloneItem = targetItem.clone(true);//this.lib.WordMo();

		targetItem.cloneItem = cloneItem;

		let texts = this.questionsTexts[this.questionIndex][this.randomIndex];
		cloneItem.normal.txt.text = texts[targetItem.index_];
		let rect = cloneItem.normal.nominalBounds;
		cloneItem.normal.cache(0, 0, rect.width, rect.height);
		cloneItem.selected.txt.text = texts[targetItem.index_];
		rect = cloneItem.selected.nominalBounds;
		cloneItem.selected.cache(0, 0, rect.width, rect.height);

		cloneItem.mouseChildren = false;
		cloneItem.scaleX = 0.68;
		cloneItem.scaleY = 0.68;

		let blackItem = this.blacks[this.blackIndex];
		cloneItem.x = blackItem.x;
		cloneItem.y = blackItem.y;
		blackItem.isSelected = true;
		blackItem.wordIndex = targetItem.index_;

		cloneItem.normal.visible = true;
		cloneItem.normal.grid.visible = false;
		cloneItem.selected.visible = false;

		this.questions.question.addChild(cloneItem);
		cloneItem.wordIndex = targetItem.index_;
		cloneItem.blackIndex = this.blackIndex;

		this.blackIndex++;

		cloneItem.on('click', (e) => {
			this.onCloneItem(e)
		});
	}

	onCloneItem(e) {
		let targetItem = e.target;
		let blackItem;
		blackItem = this.blacks[targetItem.blackIndex];
		blackItem.isSelected = false;
		blackItem.wordIndex = -1;

		let wordItem = this.words[targetItem.wordIndex];
		wordItem.normal.visible = true;
		wordItem.selected.visible = false;

		targetItem.visible = false;
		targetItem.off('click', this.onCloneItem);
		targetItem.parent.removeChild(targetItem);

		let blackIndex_ = -1;
		for (let i = 0; i < this.blacks.length; i++) {
			blackItem = this.blacks[i];
			if (!blackItem.isSelected) {
				blackIndex_ = i;
				break;
			}
		}
		if (blackIndex_ != -1) {
			this.blackIndex = blackIndex_;
		} else {
			this.blackIndex = targetItem.blackIndex
		}
	}

  createSpriteSheetBuilder(mcCon){
    let mc = mcCon.gif;
    mc.stop();
    mc._off = true;
    mcCon.removeChild(mc);
    
    if(this.questions.question){
			this.questions.question.gif._off = true;
      this.questions.question.gif.stop();
      this.questions.question.removeChild(this.questions.question.gif);
    }
    let builder = new window.createjs.SpriteSheetBuilder();
		builder.addMovieClip(mc);
		builder.addEventListener("complete", (event) => {
      let spriteSheet = event.target.spriteSheet;
      let sprite = new window.createjs.Sprite(spriteSheet);
      sprite.setTransform(mc.x, mc.y, 0.8, 0.8);
      mcCon.gif = sprite;
      mcCon.addChild(sprite);
      sprite.gotoAndPlay(0);
    });
		builder.buildAsync();
  }

	destroy() {
		if (this.questions) {
			this.questions._off = true;
			this.questions.parent && this.questions.parent.removeChild(this.questions);
      this.questions.off("click", this.defaultNullClick);
		}

		if (this.right) {
			this.right._off = true;
			this.right.parent && this.right.parent.removeChild(this.right);
			this.right.btnNext.removeAllEventListeners();
      this.right.off("click", this.defaultNullClick);
		}

		if (this.wrongs) {
			this.wrongs._off = true;
			this.wrongs.parent && this.wrongs.parent.removeChild(this.wrong);
			this.wrongs.btnNext.removeAllEventListeners();
      this.wrongs.off("click", this.defaultNullClick);
		}

		this.stagePage.removeAllEventListeners();

		this.rightAnswers = null;
		this.rightObj = null;
		this.questions = null;//7个问题页面组合
		this.home = null;//主页面
		this.wrongs = null;//错误弹层页面
		this.right = null;//错误弹层页面
		this.questionIndex = 0;//记录当点答题答到哪道题的索引
		this.blackIndex = 0;//记录当点答案索引
		this.randomIndex = 0;//随机问题也的索引
		this.words = null;//每个页面的点击字的数组
		this.blacks = null;//每个问题页面的答案字的数组

		this.stage = null;
		this.stagePage = null;
		this.lib = null;
		this.item = null;
		this.commonAttr = null;
		this.store = null;
		this.mcCallback = null;
	}
}
